package cn.edu.scnu.springbootcinema.controller;

import cn.edu.scnu.springbootcinema.entity.User;
import cn.edu.scnu.springbootcinema.service.AlipayService;
import com.alipay.api.AlipayApiException;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;

import java.util.UUID;

@Controller
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private AlipayService alipayService;

    // 发起支付请求
    @GetMapping("/create")
    @ResponseBody
    public String createPayment(
            @RequestParam String type // 套餐类型：month/quarter/year
    ) throws AlipayApiException {
        String orderNo = "CINEMA_" + UUID.randomUUID().toString().replace("-", "");
        String amount = "30.00";
        String subject = "电影网站会员服务";

        amount = switch (type) {
            case "month" -> "30.00";
            case "quarter" -> "80.00";
            case "year" -> "280.00";
            default -> amount;
        };

        return alipayService.createOrder(orderNo, amount, subject);
    }

    // 支付成功同步回调
    @GetMapping("/success")
    public String paymentSuccess(Float total_amount,HttpSession session) {
        System.out.println(total_amount);
        User user= (User) session.getAttribute("user");
        if (total_amount==30.0f){
            user.setVipDuration(30);
        }else if (total_amount==80.0f){
            user.setVipDuration(90);
        } else if (total_amount==280.0f) {
            user.setVipDuration(360);
        }
        session.setAttribute("user",user);
        return "index"; // 跳转到支付成功页面
    }

    // 支付失败处理
    @GetMapping("/fail")
    public String paymentFail() {
        return "pay/fail"; // 跳转到支付失败页面
    }
}